import React, { FC } from "react";
import { Button, Checkbox, Form, Input, Image } from 'antd';
import type { FormInstance } from 'antd/es/form';
import "./index.css"

// 引入登录接口的api
import * as api from "../../api/users"
import useStorage from "@/hooks/useStorage";
import { useNavigate } from "react-router-dom";
let img1 = require('../../images/R-C.jfif')

// 校验函数
// 校验用户名
const validatorUsername = (rules: any, value: string) => {
    // 如果通过，返回Promise.resolve,如果不通过，返回Promise.reject
    if (!value) {
        return Promise.reject('用户名不能为空！')
    }
    if (value.length < 3 || value.length > 16) {
        return Promise.reject('用户名必须是6-16位字符组成！')
    } else {
        return Promise.resolve()
    }

}

// 校验密码
const validatorPassword = (rules: any, value: string) => {
    // 如果通过，返回Promise.resolve,如果不通过，返回Promise.reject
    if (!value) {
        return Promise.reject('密码不能为空！')
    }
    if (value.length < 3 || value.length > 16) {
        return Promise.reject('密码必须是6-16位字符组成！')
    } else {
        return Promise.resolve()
    }
}

// 登录请求传递的参数的类型
declare global {
    interface loginParam {
        username: string;
        password: string;
        remeber: boolean
    }
}
const Login: FC<{}> = (props): React.ReactElement => {
    // 使用自定义的本地存储
    let [tokenStorage,tokenMethod]=useStorage('qf-token')
    let [userInfoStorage,userInfoMethod]=useStorage('user-info')
    let [permissionStorage,permissionMethod]=useStorage('btn-permission')

    // 使用跳转页面的hook
    let navigator=useNavigate()
    
    // 表单校验通过
    const onFinish = (values: loginParam) => {
        console.log('Success:', values);
        // 发起登录请求
        api.loginApi(values)
        .then((res:any)=>{
            console.log(res);

            // 如果登入成功\
            if(res.data.state){
            // 1.存token
            tokenMethod.set(res.data.token)
            // 2.存用户信息
            userInfoMethod.set(res.data.userInfo)
            // 3.存按钮权限
            permissionMethod.set(res.data.permission)
            // 跳转到主页
            navigator('/')
            }
        })
    };


    // 表单校验失败
    const onFinishFailed = (errorInfo: any) => {
        console.log('Failed:', errorInfo);
    };

    let formRef = React.createRef<FormInstance>();
    // 取消按钮
    const onReset = () => {
        formRef.current!.resetFields();
    };

    return (
        <div className="login">
            <Image width={100} height={100}
                src={img1}
            />

            <Form className="form"
                name="basic"
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                initialValues={{ remember: true }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                autoComplete="off"
            >
                <Form.Item className="form_item"
                    label="用户名 :"
                    name="username"
                    rules={[{ required: true, validator: validatorUsername }]}
                >
                    <Input className="input" />
                </Form.Item>

                <Form.Item
                    label="密码 :"
                    name="password"
                    rules={[{ required: true, validator: validatorPassword }]}
                >
                    <Input.Password className="input"/>
                </Form.Item>

                <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 8, span: 16 }}>
                    <Checkbox>记住密码？</Checkbox>
                </Form.Item>

                <Form.Item className="form_item_btn" wrapperCol={{ offset: 8, span: 16 }}>
                    <Button type="primary" htmlType="submit">
                        登录
                    </Button>
                    <Button htmlType="button" onClick={onReset} >
                        取消
                    </Button>
                </Form.Item>
            </Form>
        </div>
    )
}

export default Login